package com.jianyun.jyzs.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.SelectContactAdapter;
import com.jianyun.jyzs.base.MVPBaseActivity;
import com.jianyun.jyzs.bean.ForwardConst;
import com.jianyun.jyzs.bean.SelectedContactInfo;
import com.jianyun.jyzs.common.IntentRequestCode;
import com.jianyun.jyzs.constant.PinConstant;
import com.jianyun.jyzs.presenter.SelectPresenPresenter;
import com.jianyun.jyzs.utils.Const;
import com.jianyun.jyzs.view.iview.ISelectContactView;
import com.jianyun.jyzs.widget.CrumbView;
import com.jianyun.jyzs.widget.SelectConfig;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.rongcloud.rce.lib.SimpleResultCallback;
import cn.rongcloud.rce.lib.UserTask;
import com.jianyun.jyzs.utils.RceLog;
import cn.rongcloud.rce.lib.model.StaffInfo;

import static com.jianyun.jyzs.common.IntentRequestCode.ADD_GROUP_MEMBER;
import static com.jianyun.jyzs.common.IntentRequestCode.CHAT_GROUP_CREATE;
import static com.jianyun.jyzs.common.IntentRequestCode.GROUP_CREATE;
import static com.jianyun.jyzs.common.IntentRequestCode.GROUP_REMOVE_MEMBER;
import static com.jianyun.jyzs.common.IntentRequestCode.SEARCH_ADD_CONTACT;
import static com.jianyun.jyzs.common.IntentRequestCode.SELECT_FRIEND;


/**
 * Created by yangshijun on 2018/7/16.
 */

public class SelectContactActivity extends MVPBaseActivity<ISelectContactView,SelectPresenPresenter>
        implements ISelectContactView,View.OnClickListener {
    @BindView(R.id.createGroupCrumb)
    CrumbView departmentCrumbView;
    @BindView(R.id.departmentDivider)
    View departmentDivider;
    @BindView(R.id.selectAllCheckBox)
    ImageView selectAllCheckBox;
    @BindView(R.id.createGroupSelectAll)
    LinearLayout createGroupSelectAll;
    @BindView(R.id.selectedContactsCountTextView)
    TextView selectedContactsTextView;
    @BindView(R.id.confirmButton)
    TextView confirmButton;
    @BindView(R.id.summaryLinearLayout)
    LinearLayout summaryLinearLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private final static String TAG = SelectContactActivity.class.getSimpleName();
    public static final int FROM_CREATE_GROUP = 222;
    public static final int FROM_GROUP_ADD_STAFF = 111;
    public static final int FROM_FORWARD = 000;
    //此处不能做 public
    protected static LinkedHashMap<String, SelectedContactInfo> selectedContactInfoList;
    private SelectContactAdapter selectContactAdapter;
    public ArrayList<String> initialList;
    private int maxSelectCount = Integer.MAX_VALUE;
    protected String currentDepartId;
    private SelectConfig selectConfig;
    private ArrayList<String> uncheckableListId;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rce_activity_create_group);
        ButterKnife.bind(this);
        selectConfig = getIntent().getParcelableExtra(Const.SELECT_CONFIG);
        if (selectConfig == null) {
            selectConfig = new SelectConfig();
        }

        init();
    }

    public SelectContactAdapter onResolveAdapter() {
        return new SelectContactAdapter(this);
    }
    private void init() {
        selectedContactInfoList = new LinkedHashMap<>();
        maxSelectCount = selectConfig.getMaxSelectedNumber();

        confirmButton.setOnClickListener(this);
        setSelectedContactViewProperty();

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        createGroupSelectAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isSelectedAll = selectContactAdapter.isSelectedAll();
                if (isSelectedAll) {
                    selectContactAdapter.unselectAll();
                    selectAllCheckBox.setImageResource(R.drawable.rce_ic_checkbox_none);
                } else {
                    if (selectContactAdapter.selectAll()) {
                        selectAllCheckBox.setImageResource(R.drawable.rce_ic_checkbox_full);
                    } else {
                        exceedMaxSelectCount();
                    }
                }
            }
        });

        selectContactAdapter = onResolveAdapter();
        selectContactAdapter.setMaxSelectCount(maxSelectCount);
        selectContactAdapter.setOnFriendItemClickListener(new SelectContactAdapter.FriendItemClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SelectContactActivity.this, SelectFriendActivity.class);
                intent.putExtra(ForwardConst.FROM_WHERE, SelectContactActivity.FROM_GROUP_ADD_STAFF);
                intent.putExtra(ForwardConst.FROM_FORWARD, false);
                intent.putExtra(ForwardConst.CREATE_NEW_CHAT, false);
                SelectContactActivity.this.startActivityForResult(intent, SELECT_FRIEND);
            }
        });

        selectContactAdapter.addItemClickListener(new SelectContactAdapter.ItemClickListener() {
            @Override
            public void onEnterDepartment(Map<String, String> path) {
                departmentCrumbView.setVisibility(View.VISIBLE);
                departmentDivider.setVisibility(View.VISIBLE);
                createGroupSelectAll.setVisibility(View.VISIBLE);

                for (String key : path.keySet()) {
                    if (departmentCrumbView.getPieceCount() == 0) {
                        departmentCrumbView.setRootPiece(path.get(key), key);
                        currentDepartId = null;
                    } else {
                        departmentCrumbView.addPiece(path.get(key), key);
                        currentDepartId = key;
                    }
                }
                boolean clickable = selectContactAdapter.isClickable();
                createGroupSelectAll.setClickable(clickable);
                if (!selectContactAdapter.isSelectedAll()) {
                    selectAllCheckBox.setImageResource(R.drawable.rce_ic_checkbox_none);
                } else {
                    selectAllCheckBox.setImageResource(clickable ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_full_gray);
                }
            }

            @Override
            public void onContactChecked(SelectedContactInfo contactInfo, boolean checked) {
                if (checked) {
                    SelectedContactInfo prvContact = selectedContactInfoList.put(contactInfo.getId(), contactInfo);
                    if (prvContact != null) {
                        contactInfo.setCheckable(prvContact.isCheckable());
                    }
                } else {
                    if (contactInfo.isCheckable()) {
                        selectedContactInfoList.remove(contactInfo.getId());
                    }
                }
                setSelectedContactViewProperty();
                createGroupSelectAll.setClickable(true);
                selectAllCheckBox.setImageResource(selectContactAdapter.isSelectedAll() ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_none);
            }
        });
        departmentCrumbView.setOnPieceClickListener(new CrumbView.OnPieceClickListener() {
            @Override
            public void onPieceClick(@NonNull Object tag) {
                int stackSize = departmentCrumbView.getPieceCount();
                int position = departmentCrumbView.getPiecePosition(tag);
                currentDepartId = (String) tag;
                departmentCrumbView.backPieceTo(tag);
                if (position == 0) {
                    currentDepartId = null; // root
                }
                selectContactAdapter.onBackTo(stackSize - position - 1);
                createGroupSelectAll.setClickable(true);
                selectAllCheckBox.setImageResource(selectContactAdapter.isSelectedAll() ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_none);
            }
        });
        recyclerView.setAdapter(selectContactAdapter);
//        if (UserType.STAFF.equals(CacheTask.getInstance().getMyStaffInfo().getUserType())) {
//            OrganizationTask.getInstance().getCompanyInfo(new SimpleResultCallback<CompanyInfo>() {
//                @Override
//                public void onSuccessOnUiThread(CompanyInfo companyInfo) {
//                    selectContactAdapter.setCompanyInfo(companyInfo);
//                    selectContactAdapter.notifyDataSetChanged();
//                }
//            });
//        }


//        UserTask.getInstance().getStarContactList(new SimpleResultCallback<List<StaffInfo>>() {
//            @Override
//            public void onSuccessOnUiThread(List<StaffInfo> favContactInfos) {
//                selectContactAdapter.setContactData(favContactInfos, selectedContactInfoList.keySet());
//                selectContactAdapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onFailOnUiThread(RceErrorCode errorCode) {
//                RceLog.e(TAG, "getStarContactList : " + errorCode);
//            }
//        });
        handleInitialSelect();
    }


    private void handleInitialSelect() {
       initialList = selectConfig.getInitialSelectList();
        uncheckableListId = selectConfig.getUnCheckableList();
        if (selectConfig.isSelfCheck()){
            //uncheckableListId.remove(CacheTask.getInstance().getUserId());
            //initialList.remove(CacheTask.getInstance().getUserId());
        }
        RceLog.d("lml","uncheckableListId___________="+uncheckableListId.toString());
//        UserTask.getInstance().getStaffInfoList(initialList, new SimpleResultCallback<List<StaffInfo>>() {
//            @Override
//            public void onSuccessOnUiThread(List<StaffInfo> staffInfos) {
//                if (staffInfos != null) {
//                    for (StaffInfo memberInfo : staffInfos) {
//                        SelectedContactInfo contactInfo = new SelectedContactInfo();
//                        contactInfo.setId(memberInfo.getUserId());
//                        contactInfo.setName(memberInfo.getName());
//                        contactInfo.setPortraitUrl(memberInfo.getPortraitUrl());
//                        contactInfo.setDepartPath(memberInfo.getDepartPath());
//                        contactInfo.setDepartName(memberInfo.getDepartmentName());
//                        //如果是自己那么置灰，如果还有其他在config中处于uncheckableList的,也置灰
//                        contactInfo.setCheckable(!uncheckableListId.contains(memberInfo.getUserId()));
//                        contactInfo.setPhoneNumber(memberInfo.getMobile());
//                        selectedContactInfoList.put(contactInfo.getId(), contactInfo);
//                    }
//                    selectContactAdapter.updateSelectedCheckType();
//                    setSelectedContactViewProperty();
//                }
//            }
//        });

    }

    @Override
    final public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.selectedContactsCountTextView:
                if (selectedContactInfoList.size() > 0) {
                    Intent intent = new Intent(SelectContactActivity.this, SelectedContactActivity.class);
                    startActivityForResult(intent, GROUP_REMOVE_MEMBER);
                }
                break;
            case R.id.confirmButton:
                List<String> resultList = new ArrayList<>();
                for (String key : selectedContactInfoList.keySet()) {
                    if (uncheckableListId != null && uncheckableListId.contains(key)) {
                        continue;
                    }
                    resultList.add(key);
                }
                UserTask.getInstance().getStaffInfoList(resultList, new SimpleResultCallback<List<StaffInfo>>() {
                    @Override
                    public void onSuccessOnUiThread(List<StaffInfo> staffInfos) {
                        onConfirmButtonClick(v, (ArrayList<StaffInfo>) staffInfos);
                    }
                });
//                setBackIntent();
                break;
            default:
                break;
        }
    }

    /**
     * 正常的用户是通过startActivityForResult得到返回值，但继承的时候，也可以通过重新这个方法处理
     *
     * @param view
     * @param staffInfos
     */
    protected void onConfirmButtonClick(View view, ArrayList<StaffInfo> staffInfos) {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(Const.SELECTED_CONTACTS, staffInfos);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == GROUP_REMOVE_MEMBER) {
                setSelectedContactViewProperty();
                selectContactAdapter.updateSelectedCheckType();
                createGroupSelectAll.setClickable(true);
                selectAllCheckBox.setImageResource(selectContactAdapter.isSelectedAll() ? R.drawable.rce_ic_checkbox_full : R.drawable.rce_ic_checkbox_none);
            } else if (requestCode == CHAT_GROUP_CREATE) {
                setResult(RESULT_OK, data);
                finish();
            } else if (requestCode == SEARCH_ADD_CONTACT) {
                setSelectedContactViewProperty();
                selectContactAdapter.updateSelectedCheckType();
            } else if (requestCode == SELECT_FRIEND) {
                setSelectedContactViewProperty();
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        } else if (resultCode == GROUP_CREATE) {
            if (requestCode == SEARCH_ADD_CONTACT) {
                finish();
            }
        } else if (resultCode == ADD_GROUP_MEMBER) {
            final ArrayList<StaffInfo> staffs = data.getParcelableArrayListExtra(Const.SELECTED_CONTACTS);
            final Intent intent = new Intent();
            if (selectConfig.getMaxSelectedNumber() == PinConstant.PIN_MAX_SELECT_NUMBER) {
                UserTask.getInstance().getStaffInfoList(new ArrayList<>(selectedContactInfoList.keySet()), new SimpleResultCallback<List<StaffInfo>>() {
                    @Override
                    public void onSuccessOnUiThread(List<StaffInfo> staffInfoList) {
                        intent.putParcelableArrayListExtra(Const.SELECTED_CONTACTS, new ArrayList<>(staffInfoList));
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    }
                });
            } else {
                intent.putParcelableArrayListExtra(Const.SELECTED_CONTACTS, staffs);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    protected void setSelectedContactViewProperty() {
        int count = 0;
        for (SelectedContactInfo info : selectedContactInfoList.values()) {
            if (info.isCheckable()) {
                count++;
            }
        }
        count = count + getExtraSelectedCount();
        selectedContactsTextView.setClickable(count > 0);
        selectedContactsTextView.setTextColor(count > 0 ? getResources().getColor(R.color.color_primary) :
                getResources().getColor(R.color.color_gray_text));
        setSelectedShowText();

        confirmButton.setClickable(count > 0);
        confirmButton.setTextColor(count > 0 ?
                getResources().getColor(R.color.color_primary) :
                getResources().getColor(R.color.color_gray_text));
    }



    private void setSelectedShowText() {
        List<SelectedContactInfo> groupList = new ArrayList<>();
        int count = 0;
        if (selectedContactInfoList != null) {
            for (SelectedContactInfo selectedContactInfo : selectedContactInfoList.values()) {
                if (selectedContactInfo.isCheckable()) {
                    count++;
                    groupList.add(selectedContactInfo);
                    //if (!(selectedContactInfo.getConversationType() == null)) {
//                        if (selectedContactInfo.getConversationType().equals(Conversation.ConversationType.GROUP)) {
//                            groupList.add(selectedContactInfo);
//                        }
                   // }
                }
            }
            count = count + getExtraSelectedCount();
            int groupCount = groupList.size();
            int privateCount = count - groupCount;
            if (groupCount == 0) {
                selectedContactsTextView.setText(getString(R.string.rce_selected_contacts_count, count));
            } else if (privateCount == 0) {
                selectedContactsTextView.setText(getString(R.string.rce_selected_only_group, groupCount));
            } else {
                selectedContactsTextView.setText(getString(R.string.rce_selected_contacts_count, privateCount) + getString(R.string.rce_selected_groups_count, groupCount));
            }
        }
    }

    @Override
    public void onCreateActionBar(ActionBar actionBar) {
        super.onCreateActionBar(actionBar);
        actionBar.setTitle(getString(R.string.rce_select_contact));
        actionBar.setOptionDrawable(getResources().getDrawable(R.drawable.rce_ic_nav_option_search));
    }
    /**
     * 一般都是从系统内部选人，但是电话会议等的模块可以从手机通讯录选人，
     * 在显示选择人员数目时需要计算手机通讯里选择的人数，提供这个接口，子类可以提供手机通讯录选择的人数
     */
    protected int getExtraSelectedCount() {
        return 0;
    }
    @Override
    protected void onDestroy() {
        RceLog.d(TAG, "onDestroy");
        if (selectedContactInfoList != null) {
            selectedContactInfoList.clear();
            selectedContactInfoList = null;
        }
        super.onDestroy();
    }

    @NonNull
    @Override
    public SelectPresenPresenter createPresenter() {
        return new SelectPresenPresenter();
    }

    public void exceedMaxSelectCount() {
        if (maxSelectCount == PinConstant.PIN_MAX_SELECT_NUMBER) {
            Toast.makeText(SelectContactActivity.this, getString(R.string.rce_pin_max_receiver_number, selectConfig.getMaxSelectedNumber() - 1), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, getString(R.string.rce_select_contact_exceed_max_count), Toast.LENGTH_SHORT).show();
        }
    }

    public static LinkedHashMap<String, SelectedContactInfo> getSelectedList() {
        return selectedContactInfoList;
    }

    public SelectConfig getSelectConfig() {
        return selectConfig;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
